package utils

import (
	"fmt"
	"math/rand"
	"strings"
	"time"
)

/*
00:00-07:00,08:00-10:00,11:00-12:00
多线程不安全
*/
type MultiTimeSection struct {
	rawSections []string
	startlist   []time.Duration
	endlist     []time.Duration
	TagStr      string
}

func NewMultiTimeSection(exp string) *MultiTimeSection {
	rval := &MultiTimeSection{}
	rval.Parse(exp)
	return rval
}

func (this *MultiTimeSection) Count() int {
	return len(this.startlist)
}

func (this *MultiTimeSection) AddRandSecForStart(randSeedSec int) {
	for i := 0; i < len(this.startlist); i++ {
		if this.startlist[i] > 0 {
			this.startlist[i] += time.Second * time.Duration(rand.Intn(randSeedSec))
		}
	}
}

func (this *MultiTimeSection) AddRandSecForEnd(randSeedSec int) {
	for i := 0; i < len(this.endlist); i++ {
		if this.endlist[i] > 0 {
			this.endlist[i] += time.Second * time.Duration(rand.Intn(randSeedSec))
		}
	}
}

func (this *MultiTimeSection) String() string {
	var sb BytesBuilder
	for i := 0; i < len(this.startlist); i++ {
		if i > 0 {
			sb.AppendStr(",")
		}
		str := fmt.Sprintf("%v-%v", DurationStr(this.startlist[i]), DurationStr(this.endlist[i]))
		sb.AppendStr(str)
	}
	return sb.String()
}

func (this *MultiTimeSection) Parse(exp string) {
	sections := strings.Split(exp, ",")
	if len(sections) == 1 {
		sections = strings.Split(exp, ";")
	}
	if len(sections) == 1 {
		sections = strings.Split(exp, " ")
	}
	this.startlist = make([]time.Duration, 0, len(sections))
	this.endlist = make([]time.Duration, 0, len(sections))
	this.rawSections = make([]string, 0, len(sections))
	for i := 0; i < len(sections); i++ {
		str := Trim(sections[i])
		if len(str) == 0 {
			continue
		}
		this.rawSections = append(this.rawSections, str)
		itms := strings.SplitN(str, "-", 2)
		if len(itms) == 1 {
			itms = strings.SplitN(str, "~", 2)
		}

		this.startlist = append(this.startlist, ParseDuration(itms[0]))
		if len(itms) == 1 {
			this.endlist = append(this.endlist, 0)
		} else {
			this.endlist = append(this.endlist, ParseDuration(itms[1]))
		}
	}
}

func (this *MultiTimeSection) IsIn(val time.Duration) string {
	for i := 0; i < len(this.startlist); i++ {
		if (val >= this.startlist[i] || this.startlist[i] == 0) &&
			(val <= this.endlist[i] || this.endlist[i] == 0) {
			return this.rawSections[i]
		}
	}
	return ""
}

func (this *MultiTimeSection) IsNowIn() string {
	nowInDay := TimeInLocalToday(time.Now())
	return this.IsIn(nowInDay)
}
